/* eslint-disable no-param-reassign */
import axios from 'axios';
import { Toast } from 'vant';
import { getToken, getFundToken } from './auth';

// 创建axios实例
const service = axios.create({
  baseURL: 'http://api.demo.test.upchina.com/api/app', // api 的 base_url
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    const token = getFundToken() || getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json';
    return config;
  },
  (error) => {
    // Do something with request error
    Toast({
      message: `网络请求发送失败: ${error}`,
    });
    Promise.reject(error);
  },
);

// response 拦截器
service.interceptors.response.use(
  (response) => response.data,
  (error) => {
    let { message } = error.response.data;
    if (message.indexOf('timeout') > -1) message = '网络请求超时';
    if (
      message.indexOf('Forbidden') > -1
      || message.indexOf('No Data') > -1
      || message.indexOf('Error') > -1
      || message.indexOf('error') > -1
    ) return Promise.reject(error);
    Toast({
      message,
      duration: 2500,
    });
    return Promise.reject(error);
  },
);
export default service;
